package admin.controllers;

import helpers.DateHelper;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.DealData;

import models.DealModel;
import models.OrderModel;
import models.ProfitDetail;

import search.OrderSearchData;

@SuppressWarnings("serial")
public class SaleProfitDetailServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(SaleProfitDetailServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		process(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			boolean toFile = false;
			String action = request.getParameter("action");
			if (action != null && action.equals("toFile")) {
				toFile = true;
			}
			String strFromDate = request.getParameter("fromDate");
			String strToDate = request.getParameter("toDate");
			Date fromDate;
			Date toDate;
			DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
			try {
				fromDate = formatter.parse(strFromDate);
				request.setAttribute("fromDate", strFromDate);
			} catch (Exception e) {
				fromDate = null;
			}
			try {
				toDate = formatter.parse(strToDate);
				request.setAttribute("toDate", strToDate);
			} catch (Exception e) {
				toDate = null;
			}
			OrderSearchData orderSearch = new OrderSearchData();
			orderSearch.searchByCheckOutDate(fromDate, toDate);
			List<OrderModel> listResult = orderSearch.getListResult();
			TreeMap treeProfitDetail = new TreeMap();
			for (OrderModel orderModel : listResult) {
				if (orderModel.isCheckOut()) {
					if (treeProfitDetail.get(orderModel.getDealId()) == null) {

						ProfitDetail profitDetail = new ProfitDetail();
						DealModel deal = DealData.getById(orderModel
								.getDealId());
						profitDetail.setDealId(deal.getDealId());
						profitDetail.setDealName(deal.getShortName());
						profitDetail.setOrderQuantity(orderModel.getQuantity());
						profitDetail.setDealStartDate(DateHelper.dateToString(
								deal.getStartTime(), "dd/MM/yyyy"));
						profitDetail.setDealEndDate(DateHelper.dateToString(
								deal.getEndTime(), "dd/MM/yyyy"));
						profitDetail.setImportPrice(deal.getPriceImport());
						profitDetail.setSellPrice(deal.getPriceDiscount());
						if (orderModel.getStatus() == 4
								&& orderModel.getPaymentType() == 1
								&& orderModel.isCheckOut()) {
							profitDetail.setRealMoney(orderModel
									.getTotalPrice());
						} else if (orderModel.isCheckOut()
								&& orderModel.getPaymentType() == 2) {
							profitDetail.setBankTransferMoney(orderModel
									.getTotalPrice());
						}
						profitDetail
								.setDisplayMoney(orderModel.getTotalPrice());
						profitDetail.setTotalMoney(profitDetail
								.getBankTransferMoney()
								+ profitDetail.getRealMoney());
						treeProfitDetail.put(orderModel.getDealId(),
								profitDetail);

					} else {
						ProfitDetail profitDetail = (ProfitDetail) treeProfitDetail
								.get(orderModel.getDealId());
						profitDetail.setOrderQuantity(profitDetail
								.getOrderQuantity() + orderModel.getQuantity());
						if (orderModel.getStatus() == 4
								&& orderModel.getPaymentType() == 1
								&& orderModel.isCheckOut()) {
							profitDetail.setRealMoney(profitDetail
									.getRealMoney()
									+ orderModel.getTotalPrice());
						} else if (orderModel.isCheckOut()
								&& orderModel.getPaymentType() == 2) {
							profitDetail.setBankTransferMoney(profitDetail
									.getBankTransferMoney()
									+ orderModel.getTotalPrice());
						}
						profitDetail.setDisplayMoney(orderModel.getTotalPrice()
								+ profitDetail.getDisplayMoney());
						profitDetail.setTotalMoney(profitDetail
								.getBankTransferMoney()
								+ profitDetail.getRealMoney());
						treeProfitDetail.put(profitDetail.getDealId(),
								profitDetail);
					}
				}
			}
			List<ProfitDetail> listProfitDetail = new ArrayList<ProfitDetail>();
			Iterator entries = treeProfitDetail.entrySet().iterator();
			while (entries.hasNext()) {
				Entry thisEntry = (Entry) entries.next();
				Object value = thisEntry.getValue();
				ProfitDetail profitDetail = (ProfitDetail) value;
				listProfitDetail.add(profitDetail);
			}
			if (listProfitDetail.size() == 0) {
				listProfitDetail.add(new ProfitDetail());
			}
			request.setAttribute("result", listProfitDetail);
			if (toFile) {
				request.getRequestDispatcher(
						"/admin/pages/file_sale_profit_detail.jsp").forward(
						request, response);
			} else {
				request.getRequestDispatcher(
						"/admin/pages/sale_profit_detail.jsp").forward(request,
						response);
			}
		} catch (ServletException e) {
			System.out.println("Error when try to get sale profit !");
			log.warning("Error when try to get sale profit !");
			log.warning(e.toString());
			e.printStackTrace();
		}
	}
}
